<template>
  <div class="common-layout">
    <el-container>
      <el-header>
      </el-header>
      <el-container>
        <el-aside width="200px" class="sidebar">
          <div class="sidebar-header">
            <h3>经销商功能</h3>
          </div>
          
          <div class="sidebar-menu" v-if="authStore.isLoggedIn">
            <button 
              @click="activeTab = 'changePassword'" 
              :class="{ active: activeTab === 'changePassword' }" 
              class="menu-item"
            >修改密码</button>
            <button 
              @click="activeTab = 'listProduct'" 
              :class="{ active: activeTab === 'listProduct' }" 
              class="menu-item"
            >商品上架</button>
            <button 
              @click="switchToUpdateProduct" 
              :class="{ active: activeTab === 'updateProduct' }" 
              class="menu-item"
            >修改商品</button>
            <button 
              @click="activeTab = 'manageOrders'" 
              :class="{ active: activeTab === 'manageOrders' }" 
              class="menu-item"
            >订单管理</button>
          </div>
          
          <div v-else class="sidebar-login-prompt">
            <button @click="goHome" class="back-home-tab">前往登录</button>
          </div>
          
          <!-- 侧边栏底部退出按钮 -->
          <div class="sidebar-footer" v-if="authStore.isLoggedIn">
            <button @click="handleLogout" class="logout-btn">退出登录</button>
          </div>
          
        </el-aside>
        
        <el-main class="main-content">
          <!-- 修改密码表单 -->
          <div v-if="activeTab === 'changePassword'" class="business-card">
            <h3>修改密码</h3>
            <form @submit.prevent="handleChangePassword">
              <input v-model="changePasswordForm.accountId" placeholder="账号" required>
              <input v-model="changePasswordForm.oldPassword" type="password" placeholder="旧密码" required>
              <input v-model="changePasswordForm.newPassword" type="password" placeholder="新密码" required>
              <button type="submit">修改密码</button>
            </form>
          </div>
          
          <!-- 商品上架表单 -->
          <div v-if="activeTab === 'listProduct'" class="business-card">
            <h3>商品上架</h3>
            <form @submit.prevent="handleListProduct" enctype="multipart/form-data" class="product-form">
              <div class="form-group">
                <label>商品名称:</label>
                <input v-model="productForm.productName" placeholder="商品名称" required>
              </div>
              <div class="form-group">
                <label>商品图片:</label>
                <input type="file" @change="onImageChange" accept="image/*" multiple class="file-input">
              </div>
              <div class="form-group">
                <label>商品介绍:</label>
                <textarea v-model="productForm.productDescription" placeholder="商品介绍" required></textarea>
                <div class="ai-controls">
                  <button type="button" @click="generateProductDescription" class="ai-generate-btn">AI自动生成商品介绍</button>
                </div>
              </div>
              <div class="form-group">
                <label>商品单价:</label>
                <input v-model.number="productForm.unitPrice" type="number" step="0.01" min="0" placeholder="商品单价" required>
              </div>
              <div class="form-actions">
                <button type="submit" class="submit-btn">上架商品</button>
                <button type="button" @click="resetProductForm" class="cancel-btn">重置</button>
              </div>
            </form>
          </div>

          <!-- 商品列表和修改表单 -->
          <div v-if="activeTab === 'updateProduct'" class="business-card">
            <h3>修改商品信息</h3>
            
            <!-- 商品列表 -->
            <div v-if="!selectedProduct" class="product-list">
              <div class="list-header">
                <h4>我的商品</h4>
                <!-- <button @click="loadProducts" class="refresh-btn">刷新列表</button> -->
              </div>
              <div class="products-grid">
                <div 
                  v-for="product in products" 
                  :key="product.listingId"
                  class="product-item"
                  
                >
                  <div class="product-image">
                    <img :src="getProductImage(product)" :alt="product.productName">
                  </div>
                  <div class="product-info">
                    <h5>{{ product.productName }}</h5>
                    <p class="price">¥{{ product.unitPrice }}</p>
                    <p class="description">{{ truncateText(product.productDescription, 50) }}</p>
                    <button class="select-btn" @click="selectProduct(product)">修改</button>
                    <button class="select-btn" @click="deleteGoodsInfo(product)">删除</button>
                    <button class="select-btn" @click="handleUnlistProduct(product)" v-if="product.listingStatus == '1'">下架</button>
                    <button class="select-btn" @click="handleListProduct2(product)" v-else>上架</button>
                    
                  </div>
                </div>
              </div>
              <div v-if="products.length === 0" class="empty-state">
                <p>暂无商品，请先上架商品</p>
              </div>
            </div>
            
            <!-- 修改商品表单 -->
            <div v-if="selectedProduct" class="update-form-container">
              <h4>修改商品 - {{ selectedProduct.productName }}</h4>
              <form @submit.prevent="handleUpdateProduct" enctype="multipart/form-data" class="product-form">
                <div class="form-group">
                  <label>商品ID:</label>
                  <input v-model="updateForm.listingId" readonly>
                </div>
                <div class="form-group">
                  <label>商品名称:</label>
                  <input v-model="updateForm.productName" placeholder="商品名称" required>
                </div>
                <div class="form-group">
                  <label>商品介绍:</label>
                  <textarea v-model="updateForm.productDescription" placeholder="商品介绍" required></textarea>
                </div>
                <div class="form-group">
                  <label>商品单价:</label>
                  <input v-model.number="updateForm.unitPrice" type="number" step="0.01" min="0" placeholder="商品单价" required>
                </div>
                <div class="form-group">
                  <label>商品图片 (可选，不传则保持原图片):</label>
                  <input type="file" @change="onUpdateImageChange" accept="image/*" multiple class="file-input">
                </div>
                <div v-if="selectedProductImages.length > 0" class="image-preview">
                  <h5>当前图片预览:</h5>
                  <div class="preview-grid">
                    <img 
                      v-for="(img, index) in selectedProductImages" 
                      :key="index"
                      :src="img" 
                      alt="商品图片" 
                      class="preview-img"
                    >
                  </div>
                </div>
                <div class="form-actions">
                  <button type="submit" class="submit-btn">更新商品</button>
                  <button type="button" @click="cancelUpdate" class="cancel-btn">取消</button>
                </div>
              </form>
            </div>
          </div>

          <!-- 订单管理 -->
          <div v-if="activeTab === 'manageOrders'" class="business-card">
            <h3>订单管理</h3>
            
            <!-- 订单列表 -->
            <div v-if="!selectedOrder" class="order-list">
              <div class="list-header">
                <h4>我的订单</h4>
                <button @click="loadSellerOrders" class="refresh-btn">刷新列表</button>
              </div>
              
              <div v-if="loadingOrders" class="loading">加载中...</div>
              
              <div v-else-if="orders.length === 0" class="empty-state">
                <p>暂无订单</p>
              </div>
              
              <div v-else>
                <div 
                  v-for="order in orders.slice((currentOrderPage - 1) * ordersPerPage, currentOrderPage * ordersPerPage)" 
                  :key="order.transactionId"
                  class="order-item"
                >
                  <div class="order-header">
                    <div class="order-id">订单号: {{ order.transactionId }}</div>
                    <div :class="['order-status', order.orderStatus]">{{ getOrderStatusText(order.orderStatus) }}</div>
                  </div>
                  <div class="order-body">
                    <div class="order-info">
                      <div><strong>商品:</strong> {{ order.productName }}</div>
                      <div><strong>数量:</strong> {{ order.quantity }}</div>
                      <div><strong>单价:</strong> ¥{{ order.unitPrice }}</div>
                      <div><strong>总价:</strong> ¥{{ (order.unitPrice * order.quantity).toFixed(2) }}</div>
                      <div><strong>买家:</strong> {{ order.buyerId }}</div>
                      <div><strong>下单时间:</strong> {{ formatDate(order.purchaseTime) }}</div>
                      <div v-if="order.deliverTime"><strong>发货时间:</strong> {{ formatDate(order.deliverTime) }}</div>
                    </div>
                    <div class="order-actions">
                      <button 
                        v-if="order.orderStatus === 'paid'"
                        @click="selectOrder(order)" 
                        class="deliver-btn"
                      >发货</button>
                    </div>
                  </div>
                </div>
                
                <!-- 分页控件 -->
                <div class="pagination" v-if="totalOrderPages > 1">
                  <button @click="prevOrderPage" :disabled="currentOrderPage === 1" class="pagination-btn">
                    &lt; 上一页
                  </button>
                  <span class="page-info">第 {{ currentOrderPage }} 页 / 共 {{ totalOrderPages }} 页</span>
                  <button @click="nextOrderPage" :disabled="currentOrderPage === totalOrderPages" class="pagination-btn">
                    下一页 &gt;
                  </button>
                </div>
              </div>
            </div>
            
            <!-- 发货表单 -->
            <div v-if="selectedOrder" class="business-card">
              <h3>发货操作 - 订单号: {{ selectedOrder.transactionId }}</h3>
              
              <div class="order-detail">
                <div class="order-info">
                  <h4>订单信息</h4>
                  <div class="info-row">
                    <span class="label">商品名称：</span>
                    <span class="value">{{ selectedOrder.productName }}</span>
                  </div>
                  <div class="info-row">
                    <span class="label">商品数量：</span>
                    <span class="value">{{ selectedOrder.quantity }}</span>
                  </div>
                  <div class="info-row">
                    <span class="label">单价：</span>
                    <span class="value">¥{{ selectedOrder.unitPrice }}</span>
                  </div>
                  <div class="info-row">
                    <span class="label">总金额：</span>
                    <span class="value">¥{{ (selectedOrder.unitPrice * selectedOrder.quantity).toFixed(2) }}</span>
                  </div>
                  <div class="info-row">
                    <span class="label">买家ID：</span>
                    <span class="value">{{ selectedOrder.buyerId }}</span>
                  </div>
                  <div class="info-row">
                    <span class="label">下单时间：</span>
                    <span class="value">{{ formatDate(selectedOrder.purchaseTime) }}</span>
                  </div>
                  <div class="info-row">
                    <span class="label">订单状态：</span>
                    <span class="value" :class="{
                      'status-pending': selectedOrder.orderStatus === 'pending',
                      'status-paid': selectedOrder.orderStatus === 'paid',
                      'status-shipped': selectedOrder.orderStatus === 'shipped',
                      'status-completed': selectedOrder.orderStatus === 'completed',
                      'status-cancelled': selectedOrder.orderStatus === 'cancelled',
                      'status-returned': selectedOrder.orderStatus === 'returned'
                    }">
                      {{ getOrderStatusText(selectedOrder.orderStatus) }}
                    </span>
                  </div>
                </div>
              </div>
              
              <form @submit.prevent="handleDeliverGoods" class="deliver-form">
                <div class="form-group">
                  <label for="batchId">批次ID <span class="required">*</span></label>
                  <input 
                    id="batchId" 
                    v-model="deliverForm.batchId" 
                    type="text" 
                    placeholder="请输入批次ID" 
                    required 
                  >
                  <small class="form-hint">批次ID用于内部库存管理</small>
                </div>
                
                <div class="form-group">
                  <label for="logisticsId">物流单号 <span class="required">*</span></label>
                  <input 
                    id="logisticsId" 
                    v-model="deliverForm.logisticsId" 
                    type="text" 
                    placeholder="请输入物流单号" 
                    required
                  >
                  <small class="form-hint">物流单号用于追踪商品配送状态</small>
                </div>
                
                <div class="form-actions">
                  <button type="submit" class="submit-btn" :disabled="submitting">
                    {{ submitting ? '提交中...' : '确认发货' }}
                  </button>
                  <button type="button" @click="cancelDeliver" class="cancel-btn">
                    取消
                  </button>
                </div>
              </form>
            </div>
            
            <!-- 消息提示 -->
            <div v-if="message" :class="['message', message.type]">
              {{ message.text }}
            </div>
          </div>
        </el-main>
      </el-container>
    </el-container>
  </div>
</template>

<script>
import { useAuthStore } from '../stores/auth'
import ApiService from '../services/api'
import { ElLoading } from 'element-plus'

export default {
  name: 'SellerView',
  setup() {
    const authStore = useAuthStore()
    return { authStore }
  },
  data() {
    return {
      activeTab: 'changePassword',
      changePasswordForm: {
        accountId: '',
        oldPassword: '',
        newPassword: ''
      },
      productForm: {
        productName: '',
        productDescription: '',
        unitPrice: null
      },
      // API密钥直接在代码中设置
      kimiApiKey: 'sk-Iz7W3zbY5qL6TFMqj7ge4mGD9znXNQNGqLx07J2gPlCe1Yyf',
      productImages: [],
      products: [],
      selectedProduct: null,
      updateForm: {
        listingId: '',
        productName: '',
        productDescription: '',
        unitPrice: null,
        listingStatus: '',
      },
      updateImages: [],
      selectedProductImages: [],
      // 订单管理相关数据
      orders: [],
      selectedOrder: null,
      deliverForm: {
        batchId: '',
        logisticsId: ''
      },
      loadingOrders: false,
      submitting: false,
      message: null,
      apiService: new ApiService('seller'),
      // 分页相关数据
      currentOrderPage: 1,
      totalOrderPages: 1,
      ordersPerPage: 5,
      // 加载状态管理
      loadingInstance: null
    }
  },
  // 监听activeTab变化，当切换到对应标签时自动加载数据
  watch: {
    activeTab(newTab) {
      if (this.authStore.isLoggedIn) {
        if (newTab === 'updateProduct') {
          this.loadProducts();
        } else if (newTab === 'manageOrders') {
          this.loadSellerOrders();
        }
      }
    }
  },
  
  mounted() {
    this.authStore.initAuth()
    if (this.authStore.isLoggedIn) {
      this.activeTab = 'changePassword'
      // 自动填充当前登录账号
      this.changePasswordForm.accountId = this.authStore.accountId
    }
  },
  methods: {
    // 切换到修改商品标签并加载数据
    switchToUpdateProduct() {
      this.activeTab = 'updateProduct';
      if (this.authStore.isLoggedIn) {
        this.loadProducts();
      }
    },
  

  async handleUpdateProduct() {
  try {
    // 构造 FormData 对象
    const formData = new FormData();
    
    // 添加文本数据
    formData.append('listingId', this.updateForm.listingId);
    formData.append('productName', this.updateForm.productName);
    formData.append('productDescription', this.updateForm.productDescription);
    formData.append('unitPrice', this.updateForm.unitPrice);
    formData.append('sellerId', this.authStore.accountId);
    formData.append('listingStatus', this.updateForm.listingStatus);
    
    // 添加图片文件（如果有新上传的图片）
    for (let i = 0; i < this.updateImages.length; i++) {
      formData.append('productImages', this.updateImages[i]);
    }
    
    // 使用 apiService 更新商品信息
    const result = await this.apiService.updateGoodsInfo(formData);
    
    alert(result.message);
    
    if (result.message.includes('成功')) {
      this.cancelUpdate();
      this.loadProducts(); // 刷新商品列表
    }
  } catch (error) {
    console.error('更新商品出错:', error);
    alert('更新商品出错');
    }
  },

    
  //删除商品
async deleteGoodsInfo(product) {
  try {
    // 构造要发送的数据对象
    const requestData = {
      listingId: product.listingId,
      sellerId: this.authStore.accountId
    };
    
    // 使用 apiService 删除商品信息
    const response = await this.apiService.deleteGoodsInfo(requestData);
    
    alert(response.message);
    if (response.message.includes('成功')) {
      // 刷新商品列表
      this.loadProducts();
    }
    
    // 返回响应数据（JSON格式）
    return response;
  } catch (error) {
    console.error('删除商品出错:', error);
    alert('删除商品出错: ' + (error.message || '未知错误'));
    // 抛出错误以便调用者可以处理
    throw error;
  }
},


    // 下架商品
    async handleUnlistProduct(product) {
      try {
        // 构造 FormData 对象
        const formData = new FormData();
        
        // 添加必要的数据，确保提供所有可能需要的字段
        formData.append('listingId', product.listingId);
        formData.append('listingStatus', '0'); // 0表示下架
        formData.append('sellerId', this.authStore.accountId);
        
    
        
        // 使用 apiService 更新商品信息
        const response = await this.apiService.updateGoodsInfo(formData);
        
        alert(response.message);
        if (response.message.includes('成功')) {
          // 刷新商品列表
          this.loadProducts();
        }
      } catch (error) {
        console.error('下架商品出错:', error);
        alert('下架商品出错: ' + (error.message || '未知错误'));
      }
    },

    // 上架商品
    async handleListProduct2(product) {
      try {
        // 构造 FormData 对象
        const formData = new FormData();
        
        // 添加必要的数据，确保提供所有可能需要的字段
        formData.append('listingId', product.listingId);
        formData.append('listingStatus', '1'); // 1表示上架
        formData.append('sellerId', this.authStore.accountId);
        
        // 提供其他必要字段，避免后端处理时出现空值
        if (product.productName) {
          formData.append('productName', product.productName);
        }
        if (product.productDescription) {
          formData.append('productDescription', product.productDescription);
        }
        if (product.unitPrice !== undefined && product.unitPrice !== null) {
          formData.append('unitPrice', product.unitPrice.toString());
        }
        
        // 注意：这里不添加图片，让后端自动保留原图片路径
        
        // 使用 apiService 更新商品信息
        const response = await this.apiService.updateGoodsInfo(formData);
        
        alert(response.message);
        if (response.message.includes('成功')) {
          // 刷新商品列表
          this.loadProducts();
        }
      } catch (error) {
        console.error('上架商品出错:', error);
        alert('上架商品出错: ' + (error.message || '未知错误'));
      }
    },

   

    async handleChangePassword() {
      try {
        const result = await this.apiService.changePassword(
          this.changePasswordForm.accountId,
          this.changePasswordForm.oldPassword,
          this.changePasswordForm.newPassword
        )
        alert(result.message)
      } catch (error) {
        alert('修改密码出错')
      }
    },
    
    onImageChange(event) {
      this.productImages = Array.from(event.target.files);
    },
    
    async handleListProduct() {
      try {
        const formData = new FormData();
        
        // 添加文本数据
        formData.append('productName', this.productForm.productName);
        formData.append('productDescription', this.productForm.productDescription);
        formData.append('unitPrice', this.productForm.unitPrice);
        formData.append('sellerId', this.authStore.accountId);
        
        // 添加图片文件
        for (let i = 0; i < this.productImages.length; i++) {
          formData.append('productImages', this.productImages[i]);
        }
        
        // 发送请求到后端
        const response = await fetch('http://localhost:8080/api/seller/postGoodsInfo', {
          method: 'POST',
          body: formData
        });
        
        const result = await response.json();
        alert(result.message);
        
        // 成功后清空表单
        if (response.ok && result.message.includes('成功')) {
          this.resetProductForm();
        }
      } catch (error) {
        console.error('上架商品出错:', error);
        alert('上架商品出错');
      }
    },

    resetProductForm() {
      this.productForm = {
        productName: '',
        productDescription: '',
        unitPrice: null
      };
      this.productImages = [];
      // 重置文件输入
      const fileInput = document.querySelector('.file-input');
      if (fileInput) {
        fileInput.value = '';
      }
    },
    

    
    async generateProductDescription() {
      // 检查API密钥是否配置
      if (!this.kimiApiKey || this.kimiApiKey === 'YOUR_KIMI_API_KEY_HERE') {
        alert('API密钥未配置');
        return;
      }
      
      if (!this.productForm.productName) {
        alert('请先输入商品名称');
        return;
      }
      
      if (this.productImages.length === 0) {
        alert('请先上传商品图片');
        return;
      }
      
      try {
        // 显示全屏加载效果
        this.loadingInstance = ElLoading.service({
          lock: true,
          text: '正在生成商品介绍，请稍候...',
          background: 'rgba(255, 255, 255, 0.8)'
        });
        
        // 读取第一张图片并转换为base64
        const firstImage = this.productImages[0];
        const imageBase64 = await this.convertImageToBase64(firstImage);
        
        // 构建Kimi API请求参数
        const prompt = `请为以下商品生成一个吸引人的商品介绍：\n商品名称：${this.productForm.productName}\n\n要求：\n1. 语句简短，大概在50字左右\n2. 语言生动有趣，有吸引力\n3. 结构清晰，易于阅读\n4. 适合在线销售平台使用\n5. 易于理解`;
        
        // 调用Kimi API（使用真实的API调用）
        const response = await this.callKimiApi(prompt, imageBase64);
        
        // 将生成的介绍填充到表单中
        this.productForm.productDescription = response.content;
        
        // 关闭加载效果
        if (this.loadingInstance) {
          this.loadingInstance.close();
          this.loadingInstance = null;
        }
        
        // 显示成功消息
        this.message = {
          type: 'success',
          text: '商品介绍生成成功！'
        };
        
        // 3秒后清除消息
        setTimeout(() => {
          this.message = null;
        }, 3000);
        
      } catch (error) {
        console.error('生成商品介绍出错:', error);
        
        // 关闭加载效果
        if (this.loadingInstance) {
          this.loadingInstance.close();
          this.loadingInstance = null;
        }
        
        this.message = {
          type: 'error',
          text: `生成商品介绍失败: ${error.message || '未知错误'}`
        };
        
        // 3秒后清除消息
        setTimeout(() => {
          this.message = null;
        }, 3000);
      }
    },
    
    // 将图片转换为base64
    convertImageToBase64(file) {
      return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.onload = () => resolve(reader.result);
        reader.onerror = reject;
        reader.readAsDataURL(file);
      });
    },
    
    // 调用Kimi API
    async callKimiApi(prompt, imageBase64) {
      try {
        // Kimi API的调用URL
        const apiUrl = 'https://api.moonshot.cn/v1/chat/completions';
        
        // 使用支持图片输入的多模态模型
        const multimodalModel = 'moonshot-v1-32k'; // 这个模型支持图片输入
        
        // 构建请求体
        const requestBody = {
          model: multimodalModel,
          messages: [
            {
              role: 'system',
              content: '你是一位专业的商品描述撰写专家，擅长为各种商品生成吸引人的描述。请根据商品名称和图片信息，生成详细、专业且有吸引力的纯文本（不要生成markdown格式）商品介绍，大约在50字左右'
            },
            {
              role: 'user',
              content: [
                {
                  type: 'text',
                  text: prompt
                },
                {
                  type: 'image_url',
                  image_url: {
                    url: imageBase64
                  }
                }
              ]
            }
          ],
          temperature: 0.7
        };
        
        // 发送请求
        const response = await fetch(apiUrl, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${this.kimiApiKey}`
          },
          body: JSON.stringify(requestBody)
        });
        
        if (!response.ok) {
          const errorData = await response.json().catch(() => ({}));
          throw new Error(errorData.error?.message || `API请求失败: ${response.status}`);
        }
        
        const data = await response.json();
        return {
          content: data.choices[0].message.content
        };
      } catch (error) {
        console.error('Kimi API调用失败:', error);
        
        // 如果是图片不支持的错误，尝试使用纯文本模式重试
        if (error.message.includes('Image input not supported')) {
          console.log('当前模型不支持图片，尝试使用纯文本模式生成描述...');
          return await this.callKimiApiTextOnly(prompt);
        }
        
        throw error;
      }
    },
    
    // 纯文本模式调用Kimi API（备用方案）
    async callKimiApiTextOnly(prompt) {
      try {
        const apiUrl = 'https://api.moonshot.cn/v1/chat/completions';
        
        const requestBody = {
          model: 'moonshot-v1-8k',
          messages: [
            {
              role: 'system',
              content: '你是一位专业的商品描述撰写专家，擅长为各种商品生成吸引人的描述。请根据商品名称，生成详细、专业且有吸引力的商品介绍。'
            },
            {
              role: 'user',
              content: prompt
            }
          ],
          temperature: 0.7
        };
        
        const response = await fetch(apiUrl, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${this.kimiApiKey}`
          },
          body: JSON.stringify(requestBody)
        });
        
        if (!response.ok) {
          const errorData = await response.json().catch(() => ({}));
          throw new Error(errorData.error?.message || `API请求失败: ${response.status}`);
        }
        
        const data = await response.json();
        return {
          content: data.choices[0].message.content
        };
      } catch (error) {
        console.error('Kimi API纯文本调用失败:', error);
        throw error;
      }
    },


    
    
    goHome() {
      // 未登录时点击回到主界面
      try { this.$router.push('/') } catch (e) { window.location.href = '/' }
    },
    
    // 解析商品图片字段，处理不同的格式
    parseProductImages(imagesData) {
      if (!imagesData || imagesData === 'd' || imagesData === 'null') {
        return [];
      }
      
      try {
        // 如果是JSON字符串格式
        if (typeof imagesData === 'string' && (imagesData.startsWith('[') && imagesData.endsWith(']'))) {
          const parsed = JSON.parse(imagesData);
          return Array.isArray(parsed) ? parsed : [];
        }
        // 如果是单个字符串
        return [imagesData];
      } catch (error) {
        console.error('解析图片数据失败:', error);
        return [];
      }
    },
    
    


    async loadProducts() {
      try {
        const credentials = {
          sellerId: this.authStore.accountId
        };
        const response = await this.apiService.showGoodsInfo(credentials);
        
        // 处理商品数据，转换图片格式
        this.products = (response.products || []).map(product => {
          // 处理productImages字段
          const productImages = this.parseProductImages(product.productImages);
          return {
            ...product,
            // 添加images字段以兼容现有代码
            images: productImages.map(img => 
              img.startsWith('http') ? img : `http://localhost:8080${img}`
            )
          };
        });
      } catch (error) {
        console.error('加载商品列表失败:', error);
        alert('加载商品列表失败');
      }
    },
    
    selectProduct(product) {
      this.selectedProduct = product;
      this.updateForm = {
        listingId: product.listingId,
        productName: product.productName,
        productDescription: product.productDescription,
        unitPrice: product.unitPrice,
        listingStatus: product.listingStatus
      };
      // 加载商品图片
      this.selectedProductImages = product.images || [];
      this.updateImages = [];
    },
    
    // 订单管理相关方法
    async loadSellerOrders() {
      try {
        this.loadingOrders = true;
        const credentials = {
          sellerId: this.authStore.accountId
        };
        const response = await this.apiService.getSellerOrders(credentials);
        // 处理新的返回格式，订单数据从response.data.body获取
        this.orders = response.data && response.data.body ? response.data.body : [];
        // 反转订单顺序，让最新的订单显示在前面
        this.orders.reverse();
        // 计算总页数
        this.totalOrderPages = Math.max(1, Math.ceil(this.orders.length / this.ordersPerPage));
        this.currentOrderPage = 1; // 重置到第一页
      } catch (error) {
        console.error('加载订单列表失败:', error);
        this.showMessage('加载订单列表失败', 'error');
      } finally {
        this.loadingOrders = false;
      }
    },
    
    // 分页相关方法
    prevOrderPage() {
      if (this.currentOrderPage > 1) {
        this.currentOrderPage--;
      }
    },
    
    nextOrderPage() {
      if (this.currentOrderPage < this.totalOrderPages) {
        this.currentOrderPage++;
      }
    },
    
    selectOrder(order) {
      this.selectedOrder = order;
      this.deliverForm = {
        batchId: '',
        logisticsId: ''
      };
    },
    
    cancelDeliver() {
      this.selectedOrder = null;
      this.deliverForm = {
        batchId: '',
        logisticsId: ''
      };
    },
    
    async handleDeliverGoods() {
      try {
        this.submitting = true;
        
        // 构建查询字符串
        const params = {
          transactionId: this.selectedOrder.transactionId,
          batchId: this.deliverForm.batchId,
          logisticsId: this.deliverForm.logisticsId
        };
        
        const response = await this.apiService.deliverGoods(params);
        
        if (response && response.message) {
          if (response.message.includes('成功')) {
            this.showMessage('发货成功', 'success');
            this.selectedOrder = null;
            this.deliverForm = {
              batchId: '',
              logisticsId: ''
            };
            this.loadSellerOrders(); // 刷新订单列表
          } else {
            this.showMessage('发货失败: ' + response.message, 'error');
          }
        } else {
          this.showMessage('发货失败: 未知错误', 'error');
        }
      } catch (error) {
        console.error('发货失败:', error);
        this.showMessage('发货失败: ' + (error.message || '网络错误'), 'error');
      } finally {
        this.submitting = false;
      }
    },
    
    // 辅助方法
    getOrderStatusText(status) {
      const statusMap = {
        'pending': '待付款',
        'paid': '已付款',
        'shipped': '已发货',
        'completed': '已完成',
        'cancelled': '已取消',
        'returned': '已退货'
      };
      return statusMap[status] || status;
    },
    
    formatDate(dateString) {
      if (!dateString) return '';
      const date = new Date(dateString);
      return date.toLocaleString('zh-CN');
    },
    
    showMessage(text, type = 'info') {
      this.message = {
        text,
        type
      };
      // 3秒后自动清除消息
      setTimeout(() => {
        this.message = null;
      }, 3000);
    },
    
    getProductImage(product) {
      // 从product对象中获取第一张图片，如果没有则返回默认图片
      if (product.images && product.images.length > 0) {
        return product.images[0];
      }
      return 'https://via.placeholder.com/150?text=No+Image';
    },
    
    truncateText(text, maxLength) {
      if (!text) return '';
      return text.length > maxLength ? text.substring(0, maxLength) + '...' : text;
    },
    
    onUpdateImageChange(event) {
      this.updateImages = Array.from(event.target.files);
    },
    
   
    
    cancelUpdate() {
      this.selectedProduct = null;
      this.updateForm = {
        listingId: '',
        productName: '',
        productDescription: '',
        unitPrice: null
      };
      this.updateImages = [];
      this.selectedProductImages = [];
      // 重置文件输入
      const fileInput = document.querySelector('.file-input');
      if (fileInput) {
        fileInput.value = '';
      }
    },
    
    handleLogout() {
      this.authStore.setLogout()
      // 恢复到登录面板
      this.activeTab = 'changePassword'
      // 清空本页面会话相关表单数据
      this.changePasswordForm = { accountId: '', oldPassword: '', newPassword: '' }
      this.resetProductForm();
      this.products = [];
      this.selectedProduct = null;

      // 清除后端 cookie
      document.cookie = 'accountId=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;'
      // 统一退出后跳转回主界面
      try { this.$router.push('/') } catch (e) { window.location.href = '/' }
    }
  }
}
</script>

<style scoped>
    /* 订单列表样式 */
    .order-list {
      margin-top: 20px;
    }

    .order-item {
      border: 1px solid #e0e0e0;
      border-radius: 8px;
      padding: 15px;
      margin-bottom: 15px;
      background-color: #fff;
      box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
    }

    .order-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 10px;
      padding-bottom: 10px;
      border-bottom: 1px solid #f0f0f0;
    }

    .order-id {
      font-weight: bold;
      color: var(--text-primary);
    }

    .order-status {
      padding: 4px 8px;
      border-radius: 12px;
      font-size: 12px;
      font-weight: 500;
    }

    .order-status.paid, .order-status.待付款 {
      background-color: #fff3cd;
      color: #856404;
    }

    .order-status.shipped {
      background-color: #d1ecf1;
      color: #0c5460;
    }

    .order-status.completed {
      background-color: #d4edda;
      color: #155724;
    }

    .order-status.cancelled {
      background-color: #f8d7da;
      color: #721c24;
    }
    .order-status.pending {
      background-color: #fff3cd;
      color: #856404;
    }

    .order-status.returned {
      background-color: #f8d7da;
      color: #721c24;
    }
    
    /* 订单详情样式 */
    .order-detail {
      background-color: #f8f9fa;
      border: 1px solid #e9ecef;
      border-radius: 8px;
      padding: 20px;
      margin-bottom: 20px;
    }
    
    .order-info h4 {
      margin-top: 0;
      margin-bottom: 15px;
      color: var(--text-primary);
      font-size: 16px;
      border-bottom: 1px solid #dee2e6;
      padding-bottom: 8px;
    }
    
    .info-row {
      display: flex;
      margin-bottom: 10px;
      color: var(--text-regular);
    }
    
    .info-row .label {
      flex: 0 0 120px;
      font-weight: bold;
      color: var(--text-primary);
    }
    
    .info-row .value {
      flex: 1;
    }
    
    /* 订单状态样式 */
    .status {
      padding: 4px 8px;
      border-radius: 12px;
      font-size: 12px;
      font-weight: 500;
    }
    
    .status.pending {
      background-color: #fff3cd;
      color: #856404;
    }
    
    .status.paid {
      background-color: #e3f2fd;
      color: #1565c0;
    }
    
    .status.shipped {
      background-color: #d1ecf1;
      color: #0c5460;
    }
    
    .status.completed {
      background-color: #d4edda;
      color: #155724;
    }
    
    .status.cancelled {
      background-color: #f8d7da;
      color: #721c24;
    }
    
    .status.returned {
      background-color: #fdedec;
      color: #c82333;
    }

    .order-body {
      display: flex;
      justify-content: space-between;
      align-items: flex-start;
    }

    .order-info {
      flex: 1;
    }

    .order-info > div {
      margin-bottom: 5px;
      color: #666;
    }

    .order-actions {
      margin-left: 20px;
    }

    .deliver-btn {
      background-color: var(--primary-color);
      color: white;
      border: none;
      padding: 8px 16px;
      border-radius: 4px;
      cursor: pointer;
      font-size: 14px;
    }

    .deliver-btn:hover {
      background-color: var(--primary-dark);
    }

    .empty-state {
      text-align: center;
      padding: 40px 0;
      color: var(--text-secondary);
    }

    .loading {
      text-align: center;
      padding: 20px 0;
      color: var(--text-regular);
    }

    /* 消息提示样式 */
    .message {
      padding: 10px 15px;
      margin-bottom: 15px;
      border-radius: 4px;
      font-size: 14px;
    }

    .message.success {
      background-color: #d4edda;
      color: #155724;
      border: 1px solid #c3e6cb;
    }

    .message.error {
      background-color: #f8d7da;
      color: #721c24;
      border: 1px solid #f5c6cb;
    }

    .message.info {
      background-color: #d1ecf1;
      color: #0c5460;
      border: 1px solid #bee5eb;
    }
    
    /* 发货表单样式 */
    .order-summary {
      background-color: #f8f9fa;
      border: 1px solid #e9ecef;
      border-radius: 8px;
      padding: 20px;
      margin-bottom: 20px;
    }
    
    .order-summary h4 {
      margin-top: 0;
      margin-bottom: 15px;
      color: var(--text-primary);
      font-size: 16px;
    }
    
    .summary-grid {
      display: grid;
      grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
      gap: 10px;
    }
    
    .summary-grid > div {
      padding: 5px 0;
      color: var(--text-regular);
    }
    
    .deliver-form {
      max-width: 600px;
      margin: 0 auto;
    }
    
    .required {
      color: var(--danger-color);
      font-size: 16px;
    }
    
    .form-hint {
      display: block;
      margin-top: 5px;
      color: var(--text-secondary);
      font-size: 12px;
    }
    
    .submit-btn {
      background-color: var(--success-color);
      color: white;
      border: none;
      padding: 10px 20px;
      border-radius: 4px;
      cursor: pointer;
      font-size: 14px;
      margin-right: 10px;
    }
    
    .submit-btn:hover:not(:disabled) {
      background-color: #529b2e;
    }
    
    .submit-btn:disabled {
      background-color: #c0c4cc;
      cursor: not-allowed;
    }
    
    .cancel-btn {
      background-color: #f56c6c;
      color: white;
      border: none;
      padding: 10px 20px;
      border-radius: 4px;
      cursor: pointer;
      font-size: 14px;
    }
    
    .cancel-btn:hover {
      background-color: #e64e4e;
    }
/* 新色彩主题 */
:root {
  /* 主色调 - 现代蓝色系 */
  --primary-color: #409EFF;
  --primary-light: #ecf5ff;
  --primary-dark: #3375b9;
  
  /* 辅助色 */
  --success-color: #67C23A;
  --warning-color: #E6A23C;
  --danger-color: #F56C6C;
  --info-color: #909399;
  
  /* 中性色 - 更柔和的灰色 */
  --text-primary: #2c3e50;
  --text-regular: #5a6c7d;
  --text-secondary: #8796a8;
  --text-placeholder: #c0c8d1;
  
  /* 背景色 - 渐变效果 */
  --bg-gradient: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  --bg-card: #ffffff;
  --bg-sidebar: linear-gradient(180deg, #304156 0%, #1f2d3d 100%);
  
  /* 边框色 */
  --border-color: #e4e7ed;
  --border-light: #ebeef5;
  --border-lighter: #f2f6fc;
  
  /* 阴影 */
  --shadow-card: 0 4px 20px rgba(0, 0, 0, 0.08);
  --shadow-hover: 0 6px 24px rgba(0, 0, 0, 0.1);
  --shadow-header: 0 2px 12px rgba(0, 0, 0, 0.1);
}

/* 整体布局 */
.common-layout {
  height: 100vh;
  width: 100vw;
  background: var(--bg-gradient);
}

.el-container {
  height: 100%;
}

/* 顶部导航栏 */
.el-header {
  background: #ffffff;
  box-shadow: var(--shadow-header);
  display: flex;
  align-items: center;
  padding: 0 24px;
  border-bottom: 1px solid var(--border-color);
  height: 0px;
  line-height: 60px;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  height: 100%;
  box-sizing: border-box;
  padding: 0 24px;
}

.header-content h2 {
  margin: 0;
  color: var(--text-primary);
  font-size: 18px;
  font-weight: 600;
}

.header-user-info {
  color: var(--text-regular);
  font-size: 14px;
}

/* 侧边栏 */
.el-aside {
  background: var(--bg-sidebar);
  box-shadow: 2px 0 8px 0 rgba(29, 35, 41, 0.1);
  overflow-y: auto;
}

.sidebar-header {
  padding: 20px;
  border-bottom: 1px solid #2d3a4b;
  color: white;
  text-align: center;
}

.sidebar-header h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
}

.sidebar-menu {
  padding: 16px 0;
}

.menu-item {
  width: 100%;
  padding: 12px 24px;
  border: none;
  background: transparent;
  color: rgba(255, 255, 255, 0.7);
  text-align: left;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s ease;
  display: block;
}

.menu-item:hover {
  background: rgba(255, 255, 255, 0.1);
  color: #ffffff;
}

.menu-item.active {
  background: var(--primary-color);
  color: #ffffff;
}

.sidebar-login-prompt {
  padding: 20px;
  text-align: center;
}

.back-home-tab {
  padding: 10px 20px;
  margin: 10px auto;
  border: 1px solid var(--primary-color);
  background: transparent;
  color: var(--primary-color);
  cursor: pointer;
  display: block;
  width: 100%;
  border-radius: 4px;
  font-size: 14px;
  transition: all 0.3s ease;
}

.back-home-tab:hover {
  background: var(--primary-color);
  color: white;
}

.sidebar-footer {
  margin-top: auto;
  margin-top:260%;
  padding: 16px;
  width: 100%;
  box-sizing: border-box;
}

.logout-btn {
  width: 80%;
  margin: 0 auto;
  display: block;
  padding: 10px 20px;
  border: none;
  background: var(--danger-color);
  color: white;
  cursor: pointer;
  border-radius: 4px;
  font-size: 14px;
  transition: all 0.3s ease;
}

.logout-btn:hover {
  background: #e4393c;
}

/* 主内容区 */
.el-main {
  padding: 24px;
  overflow-y: auto;
  background: transparent;
}

.main-content {
  min-height: 100%;
}

/* 业务卡片 */
.business-card {
  background: var(--bg-card);
  border-radius: 8px;
  box-shadow: var(--shadow-card);
  padding: 24px;
  margin-bottom: 20px;
  transition: all 0.3s ease;
  border: 1px solid var(--border-light);
}

.business-card:hover {
  transform: translateY(-2px);
  box-shadow: var(--shadow-hover);
}

.business-card h3 {
  color: var(--text-primary);
  margin-bottom: 20px;
  font-size: 18px;
  font-weight: 600;
}

/* 商品列表样式 */
.product-list {
  margin-bottom: 20px;
}

.list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.list-header h4 {
  margin: 0;
  color: var(--text-primary);
}

.refresh-btn {
  padding: 6px 16px;
  background: var(--primary-color);
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
}

.refresh-btn:hover {
  background: var(--primary-dark);
}

.products-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  gap: 20px;
}

.product-item {
  border: 1px solid var(--border-color);
  border-radius: 8px;
  padding: 16px;
  cursor: pointer;
  transition: all 0.3s ease;
  background: white;
}

.product-item:hover {
  border-color: var(--primary-color);
  box-shadow: var(--shadow-hover);
  transform: translateY(-2px);
}

.product-image {
  width: 100%;
  height: 150px;
  overflow: hidden;
  border-radius: 4px;
  margin-bottom: 12px;
}

.product-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.product-info h5 {
  margin: 0 0 8px 0;
  color: var(--text-primary);
}

.product-info .price {
  color: var(--danger-color);
  font-weight: bold;
  margin: 0 0 8px 0;
}

.product-info .description {
  color: var(--text-secondary);
  font-size: 14px;
  margin: 0 0 12px 0;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.select-btn {
  width: 100%;
  padding: 8px;
  background: var(--primary-color);
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
}

.select-btn:hover {
  background: var(--primary-dark);
}

.empty-state {
  text-align: center;
  padding: 40px;
  color: var(--text-secondary);
}

/* 更新表单样式 */
.update-form-container {
  max-width: 600px;
  margin: 0 auto;
}

.image-preview {
  margin-top: 20px;
}

.image-preview h5 {
  margin-bottom: 12px;
  color: var(--text-regular);
}

.preview-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(100px, 1fr));
  gap: 10px;
}

.preview-img {
  width: 100px;
  height: 100px;
  object-fit: cover;
  border: 1px solid var(--border-color);
  border-radius: 4px;
}

/* 表单样式 */
.business-card form {
  max-width: 500px;
  margin: 0 auto;
}

.business-card input, .business-card textarea, .business-card select {
  width: 100%;
  padding: 10px;
  margin: 10px 0;
  border: 1px solid var(--border-color);
  border-radius: 4px;
  transition: border-color 0.3s ease;
}

.business-card input:focus, .business-card textarea:focus, .business-card select:focus {
  outline: none;
  border-color: var(--primary-color);
}

.business-card button[type="submit"] {
  width: 100%;
  padding: 10px;
  background: var(--primary-color);
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 16px;
  transition: background-color 0.3s ease;
}

.business-card button[type="submit"]:hover {
  background: var(--primary-dark);
}

/* 商品上架表单样式 */
.product-form {
  max-width: 500px;
  margin: 0 auto;
}

.form-group {
  margin-bottom: 1.25rem;
}

.form-group label {
  display: block;
  margin-bottom: 0.5rem;
  font-weight: bold;
  color: var(--text-regular);
}

.form-group input, .form-group textarea, .form-group select {
  width: 100%;
  padding: 8px 12px;
  border: 1px solid var(--border-color);
  border-radius: 4px;
  transition: border-color 0.3s ease;
}

.form-group input:focus, .form-group textarea:focus, .form-group select:focus {
  outline: none;
  border-color: var(--primary-color);
}

.form-group textarea {
  height: 100px;
  resize: vertical;
}

.ai-controls {
  display: flex;
  gap: 10px;
  margin-top: 0.5rem;
}

.ai-generate-btn {
  padding: 8px 16px;
  background: var(--primary-color);
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: background-color 0.3s ease;
}

.ai-generate-btn:hover {
  background: #409eff;
}

.ai-generate-btn:disabled {
  background: #a0cfff;
  cursor: not-allowed;
}



.save-btn {
  padding: 8px 16px;
  background: var(--success-color);
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.save-btn:hover {
  background: #5daf34;
}

.file-input {
  padding: 6px 12px;
}

.form-actions {
  display: flex;
  gap: 1rem;
  margin-top: 1.5rem;
}

.submit-btn {
  flex: 2;
  padding: 10px;
  background: var(--success-color);
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 16px;
  transition: background-color 0.3s ease;
}

.submit-btn:hover {
  background: #5daf34;
}

.cancel-btn {
  flex: 1;
  padding: 10px;
  background: var(--danger-color);
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 16px;
  transition: background-color 0.3s ease;
}

.cancel-btn:hover {
  background: #e4393c;
}

/* 分页样式 */
.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 1rem;
  gap: 1rem;
}

.pagination-btn {
  padding: 8px 16px;
  border: 1px solid var(--border-color);
  background: white;
  cursor: pointer;
  border-radius: 4px;
  font-size: 14px;
  transition: all 0.3s ease;
}

.pagination-btn:disabled {
  background: #f5f5f5;
  color: var(--text-placeholder);
  cursor: not-allowed;
}

.pagination-btn:not(:disabled):hover {
  background: var(--primary-color);
  color: white;
  border-color: var(--primary-color);
}

.page-info {
  color: var(--text-regular);
  font-weight: bold;
  font-size: 14px;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .el-container {
    grid-template-columns: 1fr;
    grid-template-rows: 60px 1fr;
    grid-template-areas: 
      "header"
      "main";
  }
  
  .el-aside {
    display: none; /* 移动端隐藏侧边栏 */
  }
  
  .el-main {
    padding: 16px;
  }
  
  .header-content {
    flex-direction: column;
    gap: 10px;
    padding: 10px 0;
  }
  
  .business-card {
    padding: 16px;
  }
  
  .form-actions {
    flex-direction: column;
  }
}
</style>